/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */

Ext.namespace("Admin");


/**
 * Organization edit dialog.
 *
 * @param config the configuration.
 */
Admin.OrganizationDialog = function(config) {
	Admin.OrganizationDialog.superclass.constructor.call(this, config);
};

Ext.extend(Admin.OrganizationDialog, Ext.Window, {

	initComponent: function() {

		Ext.apply(this, {
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-org-edit',
			title: MSG['organization'],
			bodyStyle:'padding:5px'
		});

		this.items = new Ext.FormPanel({
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['organization.name'],
				maxLength: 50,
				allowBlank: false
			}, {
				xtype: 'lovcombo',
				fieldLabel: MSG['organization.provinces'],
				hiddenName: 'provinces',
				width: 160,
				mode: 'local',
				store: new Ext.data.SimpleStore({
					fields: ['id', 'name'],
					data: Common.Provinces
				}),
				valueField: 'id',
				displayField: 'name',
				triggerAction: 'all'
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});


		Admin.OrganizationDialog.superclass.initComponent.call(this);
	},

	onSave: function() {
		var theForm = this.items.items[0].getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/admin/organization/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onCancel: function() {
		this.close();
	},

	onSaveSuccess: function(/*form, action*/) {
		this.close();
		notifySuccess(MSG['organization'], MSG['update.success']);
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['organization'], MSG['update.error']);
	}

});

/**
 * Organization search panel.
 *
 * @param config the configuration.
 */
Admin.OrganizationSearchPanel = function(config) {
	Admin.OrganizationSearchPanel.superclass.constructor.call(this, config);
};

Ext.extend(Admin.OrganizationSearchPanel, Ext.Panel, {

	searchForm: null,

	waitDlg: null,

	resultsStore: null,

	pageToolbar: null,

	resultsGrid: null,

	editForm: null,

	initComponent: function() {

		this.layout = 'border';
		this.title = MSG['organizations'];
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-org';

		// Tools
		this.tools = [{
			id: 'close',
			handler: this.onClose,
			scope: this
		}];

		// Search form
		this.searchForm = new Ext.FormPanel({
			region: 'west',
			split: true,
			collapsible: true,
			title: MSG['search.title'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['organization.name'],
				maxLength: 50
			}, {
				xtype: 'lovcombo',
				fieldLabel: MSG['organization.provinces'],
				hiddenName: 'provinces',
				width: 160,
				mode: 'local',
				store: new Ext.data.SimpleStore({
					fields: ['id', 'name'],
					data: Common.Provinces
				}),
				valueField: 'id',
				displayField: 'name',
				triggerAction: 'all'
			}],
			buttons: [{
				text: MSG['button.search'],
				iconCls: 'icon-search',
				handler: this.onSearch,
				scope: this
			}, {
				text: MSG['button.reset'],
				iconCls: 'icon-cancel',
				handler: this.onReset,
				scope: this
			}]
		});

		// Store
		this.resultsStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/admin/organization/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			fields: ['id', 'name', 'provinces']
		});
		this.resultsStore.on("beforeload",
				function() {
					this.waitDlg = Ext.Msg.wait(MSG['wait.title'], MSG['wait.text']);
					this.resultsStore.baseParams = this.searchForm.getForm().getRawValues();
				}, this);
		this.resultsStore.on("load",
				function() {
					this.waitDlg.hide();
				}, this);

		// Pagination toolbar
		this.pageToolbar = new Ext.PagingToolbar({
			store: this.resultsStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin(MSG['page.size'])]
		});

		// Grid
		this.resultsGrid = new Ext.grid.GridPanel({
			title: MSG['result.title'],
			region: 'center',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				{header: MSG['organization.id'], dataIndex: 'id', width: 40, sortable: true},
				{header: MSG['organization.name'], dataIndex: 'name', width: 140, sortable: true},
				{header: MSG['organization.provinces'], dataIndex: 'provinces', width: 100, sortable: true, renderer: function(r) {
					var v = '';
					if (r != null && r.length > 0) {
						var i = 0;
						for (; i < r.length; ++i) {
							v += r[i].name;
							if (i < r.length - 1) v += ',';
						}
					}
					return v;
				}}
			]),
			store: this.resultsStore,
			bbar: this.pageToolbar
		});

		// Editor
		this.editForm = new Ext.FormPanel({
			region: 'east',
			split: true,
			collapsible: true,
			collapsed: true,
			title: MSG['button.newfem'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'id',
				value: 0
			}, {
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['organization.name'],
				maxLength: 50,
				allowBlank: false
			}, {
				xtype: 'lovcombo',
				fieldLabel: MSG['organization.provinces'],
				hiddenName: 'provinces',
				width: 160,
				mode: 'local',
				store: new Ext.data.SimpleStore({
					fields: ['id', 'name'],
					data: Common.Provinces
				}),
				valueField: 'id',
				displayField: 'name',
				triggerAction: 'all'
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});

		this.items = [this.searchForm, this.resultsGrid, this.editForm];

		this.pageToolbar.doLoad(0);

		this.resultsGrid.on("rowclick", this.onSelected, this);

		Admin.OrganizationSearchPanel.superclass.initComponent.call(this);
	},

	onClose: function() {
		Main.app.addPanel(null);
	},

	onSearch: function() {
		this.editForm.collapse();
		this.pageToolbar.doLoad(0);
	},

	onReset: function() {
		this.searchForm.getForm().reset();
		this.pageToolbar.doLoad(0);
	},

	onSelected: function(grid, rowIndex/*, evt*/) {
		this.searchForm.collapse();
		this.editForm.expand();

		var record = grid.getStore().getAt(rowIndex);
		var data = {};
		Ext.apply(data, record.data);

		// Remote combo set value... https://yui-ext.com/forum/showthread.php?t=20803

		var theForm = this.editForm.getForm();
		theForm.loadRecord({data: data});

		var provincesCombo = theForm.findField('provinces');
		var provinces = data.provinces;
		var pv = '';
		for (var i = 0; i < provinces.length; ++i) {
			pv += '' + provinces[i].id;
			if (i < provinces.length - 1) pv += ',';
		}
		provincesCombo.setValue(pv);
		this.editForm.setTitle(MSG['edit.title']);
	},

	onSave: function() {
		var theForm = this.editForm.getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/admin/organization/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onSaveSuccess: function(/*form, action*/) {
		notifySuccess(MSG['organization'], MSG['update.success']);
		this.pageToolbar.onClick("refresh");
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['organization'], MSG['update.error']);
	},

	onCancel: function() {
		this.editForm.getForm().reset();
		this.editForm.setTitle(MSG['button.newfem']);		
	}

});

// Register user search panel
Ext.reg('org-search', Admin.OrganizationSearchPanel);


/**
 * Module definition.
 */
MODULES['3_admin_org'] = {

	menu: null,

	init: function() {

		// Initialize common menu
		this.menu = new Ext.menu.Menu({
			items: [{
				text: MSG['organization.search'],
				iconCls: 'icon-org-find',
				handler: this.onFind,
				scope: this
			},{
				text: MSG['organization.new'],
				iconCls: 'icon-org-edit',
				handler: this.onNew,
				scope: this
			},{
				text: MSG['organization.check'],
				iconCls: 'icon-org-check',
				handler: this.onCheck,
				scope: this
			}]
		});


		// Add menu to toolbar
		Main.app.mainToolbar.add({
			text: MSG['organizations'],
			iconCls: 'icon-org',
			menu: this.menu
		});

	},

	onFind: function() {
		var searchPanel = new Admin.OrganizationSearchPanel();
		Main.app.addPanel(searchPanel);
	},

	onNew: function() {
		var editDialog = new Admin.OrganizationDialog();
		editDialog.show();
	},

	onCheck: function() {
		Ext.Ajax.request({
			waitMsg: MSG['wait.message'],
			waitTitle: MSG['wait.title'],
			url: CONTEXT_PATH + '/secure/admin/organization/check.json',
			success: function(/*response, options*/){
				notifySuccess(MSG['check'], MSG['check.success']);
			},
			failure: function(){
				notifyError(MSG['check'], MSG['check.error']);
			}
		});
	}

};